<template>
  <div class="app-container">
    <div v-loading="loading">
      <!-- 根据账户状态显示提示信息 -->
      <el-alert
        v-if="accountInfo && accountInfo.auditStatus === '0'"
        type="info"
        :closable="false"
        title="您的支付账户信息已提交，正在审核中"
        show-icon
      />
      <el-alert
        v-if="accountInfo && accountInfo.auditStatus === '1'"
        type="success"
        :closable="false"
        title="您的支付账户信息已审核通过"
        show-icon
      />
      <el-alert
        v-if="accountInfo && accountInfo.auditStatus === '2'"
        type="error"
        :closable="false"
        title="您的支付账户信息审核未通过，请修改后重新提交"
        :description="accountInfo.auditRemark || '未提供审核失败原因'"
        show-icon
      />
      <el-alert
        v-if="accountInfo && accountInfo.auditStatus === '99'"
        type="warning"
        :closable="false"
        title="您的支付账户信息已暂存，请完善信息后提交审核"
        show-icon
      />

      <!-- 表单内容 -->
      <div class="mt20">
        <!-- 账户类型选择 -->
        <div class="section-block">
          <div class="section-header">
            <span>选择商户类型</span>
          </div>
          <div class="section-content">
            <el-radio-group v-model="accountType" @change="handleAccountTypeChange" :disabled="!canEdit">
              <el-radio label="1">个人</el-radio>
              <el-radio label="2">企业</el-radio>
            </el-radio-group>
          </div>
        </div>

        <!-- 配置表单 -->
        <div class="section-block mt20">
          <div class="section-header">
            <span>{{ accountType === '1' ? '个人商户配置' : '企业商户配置' }}</span>
          </div>
          <div class="section-content">
            <!-- 表单内容 -->
            <el-form ref="accountFormRef" :model="accountForm" :rules="rules" label-width="150px" :disabled="!canEdit">
              <!-- 基本信息 -->
              <h3 class="form-section-title">基本信息</h3>
              <el-form-item label="商户名称" prop="accountName">
                <el-input v-model="accountForm.accountName" placeholder="请输入商户名称" class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="联系手机" prop="contactPhone">
                <el-input v-model="accountForm.contactPhone" placeholder="请输入联系手机号" class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="联系邮箱" prop="contactEmail">
                <el-input v-model="accountForm.contactEmail" placeholder="请输入联系邮箱" class="form-input"></el-input>
              </el-form-item>

              <!-- 个人商户-身份证照片信息 -->
              <template v-if="accountType === '1'">
                <h3 class="form-section-title">身份证照片信息</h3>
                <el-form-item label="身份证人像面照片" prop="idCardFrontImg">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="(res) => handleUploadSuccess(res, 'idCardFrontImg')"
                    :before-upload="beforeUpload"
                    :disabled="!canEdit">
                    <div class="upload-box">
                      <img v-if="accountForm.idCardFrontImg" :src="accountForm.idCardFrontImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      <div class="upload-text">点击上传</div>
                    </div>
                  </el-upload>
                </el-form-item>
                <el-form-item label="身份证国徽面照片" prop="idCardBackImg">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="(res) => handleUploadSuccess(res, 'idCardBackImg')"
                    :before-upload="beforeUpload"
                    :disabled="!canEdit">
                    <div class="upload-box">
                      <img v-if="accountForm.idCardBackImg" :src="accountForm.idCardBackImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      <div class="upload-text">点击上传</div>
                    </div>
                  </el-upload>
                </el-form-item>
                <el-form-item label="姓名" prop="accountHolder">
                  <el-input v-model="accountForm.accountHolder" placeholder="请输入身份证姓名" class="form-input"></el-input>
                </el-form-item>
                <el-form-item label="身份证号码" prop="idCardNo">
                  <el-input v-model="accountForm.idCardNo" placeholder="请输入身份证号码" class="form-input"></el-input>
                </el-form-item>
              </template>

              <!-- 企业商户-营业执照照片 -->
              <template v-if="accountType === '2'">
                <h3 class="form-section-title">营业执照照片</h3>
                <el-form-item label="营业执照照片" prop="businessLicenseImg">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="(res) => handleUploadSuccess(res, 'businessLicenseImg')"
                    :before-upload="beforeUpload"
                    :disabled="!canEdit">
                    <div class="upload-box">
                      <img v-if="accountForm.businessLicenseImg" :src="accountForm.businessLicenseImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      <div class="upload-text">点击上传</div>
                    </div>
                  </el-upload>
                </el-form-item>
                <el-form-item label="公司名称" prop="companyName">
                  <el-input v-model="accountForm.companyName" placeholder="请输入营业执照上的公司名称" class="form-input"></el-input>
                </el-form-item>
                <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
                  <el-input v-model="accountForm.unifiedSocialCreditCode" placeholder="请输入统一社会信用代码" class="form-input"></el-input>
                </el-form-item>

                <h3 class="form-section-title">法人身份证照片</h3>
                <el-form-item label="身份证人像面照片" prop="legalPersonIdCardFrontImg">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="(res) => handleUploadSuccess(res, 'legalPersonIdCardFrontImg')"
                    :before-upload="beforeUpload"
                    :disabled="!canEdit">
                    <div class="upload-box">
                      <img v-if="accountForm.legalPersonIdCardFrontImg" :src="accountForm.legalPersonIdCardFrontImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      <div class="upload-text">点击上传</div>
                    </div>
                  </el-upload>
                </el-form-item>
                <el-form-item label="身份证国徽面照片" prop="legalPersonIdCardBackImg">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="(res) => handleUploadSuccess(res, 'legalPersonIdCardBackImg')"
                    :before-upload="beforeUpload"
                    :disabled="!canEdit">
                    <div class="upload-box">
                      <img v-if="accountForm.legalPersonIdCardBackImg" :src="accountForm.legalPersonIdCardBackImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      <div class="upload-text">点击上传</div>
                    </div>
                  </el-upload>
                </el-form-item>
                <el-form-item label="法人姓名" prop="legalPersonName">
                  <el-input v-model="accountForm.legalPersonName" placeholder="请输入法人姓名" class="form-input"></el-input>
                </el-form-item>
                <el-form-item label="法人身份证号码" prop="legalPersonIdCardNo">
                  <el-input v-model="accountForm.legalPersonIdCardNo" placeholder="请输入法人身份证号码" class="form-input"></el-input>
                </el-form-item>

                <h3 class="form-section-title">开户许可证照片</h3>
                <el-form-item label="开户许可证照片" prop="accountOpeningLicenseImg">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="(res) => handleUploadSuccess(res, 'accountOpeningLicenseImg')"
                    :before-upload="beforeUpload"
                    :disabled="!canEdit">
                    <div class="upload-box">
                      <img v-if="accountForm.accountOpeningLicenseImg" :src="accountForm.accountOpeningLicenseImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      <div class="upload-text">点击上传</div>
                    </div>
                  </el-upload>
                </el-form-item>
              </template>

              <!-- 通用-经营场所照片 -->
              <h3 class="form-section-title">经营场所照片</h3>
              <el-form-item label="经营场所照片" prop="businessPlaceImg">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="(res) => handleUploadSuccess(res, 'businessPlaceImg')"
                  :before-upload="beforeUpload"
                  :disabled="!canEdit">
                  <div class="upload-box">
                    <img v-if="accountForm.businessPlaceImg" :src="accountForm.businessPlaceImg" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    <div class="upload-text">点击上传</div>
                  </div>
                </el-upload>
              </el-form-item>

              <!-- 结算账户 -->
              <h3 class="form-section-title">结算账户</h3>
              <el-form-item label="账户类型" prop="settlementType">
                <el-radio-group v-model="accountForm.settlementType">
                  <el-radio label="1">对公账户</el-radio>
                  <el-radio label="2">法人账户</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="开户银行" prop="bankName">
                <el-input v-model="accountForm.bankName" placeholder="请输入开户银行" class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="银行账户" prop="bankAccount">
                <el-input v-model="accountForm.bankAccount" placeholder="请输入银行账户" class="form-input"></el-input>
              </el-form-item>

              <!-- 操作按钮 -->
              <el-form-item v-if="canEdit">
                <el-button type="primary" @click="submitForm(false)" :loading="submitLoading">提交</el-button>
                <el-button type="success" @click="submitForm(true)" :loading="tempLoading">暂存</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getAccountInfo, saveAccount, saveDraftAccount } from '@/api/payment/account'
import { getToken } from '@/utils/auth'

export default {
  name: "PaymentSetting",
  data() {
    return {
      loading: false,
      submitLoading: false,
      tempLoading: false,
      accountInfo: null,
      accountType: '1', // 默认选择个人类型
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadUrl: import.meta.env.VITE_APP_BASE_API + "/file/upload", // 上传地址
      accountForm: {
        // 基本信息
        accountId: '',
        accountName: '',
        accountType: '1', // 1-个人 2-企业
        contactPhone: '',
        contactEmail: '',
        
        // 个人商户-身份证信息
        idCardFrontImg: '',
        idCardBackImg: '',
        accountHolder: '', // 对应个人姓名
        idCardNo: '',
        
        // 企业商户-营业执照
        businessLicenseImg: '',
        companyName: '',
        unifiedSocialCreditCode: '',
        
        // 企业商户-法人身份证
        legalPersonIdCardFrontImg: '',
        legalPersonIdCardBackImg: '',
        legalPersonName: '',
        legalPersonIdCardNo: '',
        
        // 企业商户-开户许可证
        accountOpeningLicenseImg: '',
        
        // 经营场所照片
        businessPlaceImg: '',
        
        // 结算账户
        settlementType: '1', // 结算账户类型，1-对公账户，2-法人账户
        bankName: '',
        bankAccount: ''
      },
      rules: {
        // 基本信息验证规则
        accountName: [
          { required: true, message: '请输入商户名称', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系手机', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        contactEmail: [
          { required: true, message: '请输入联系邮箱', trigger: 'blur' },
          { pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        
        // 个人商户-身份证信息验证规则
        idCardFrontImg: [
          { required: true, message: '请上传身份证人像面照片', trigger: 'change' }
        ],
        idCardBackImg: [
          { required: true, message: '请上传身份证国徽面照片', trigger: 'change' }
        ],
        accountHolder: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        idCardNo: [
          { required: true, message: '请输入身份证号码', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
        ],
        
        // 企业商户-营业执照验证规则
        businessLicenseImg: [
          { required: true, message: '请上传营业执照照片', trigger: 'change' }
        ],
        companyName: [
          { required: true, message: '请输入公司名称', trigger: 'blur' }
        ],
        unifiedSocialCreditCode: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
        ],
        
        // 企业商户-法人身份证验证规则
        legalPersonIdCardFrontImg: [
          { required: true, message: '请上传法人身份证人像面照片', trigger: 'change' }
        ],
        legalPersonIdCardBackImg: [
          { required: true, message: '请上传法人身份证国徽面照片', trigger: 'change' }
        ],
        legalPersonName: [
          { required: true, message: '请输入法人姓名', trigger: 'blur' }
        ],
        legalPersonIdCardNo: [
          { required: true, message: '请输入法人身份证号码', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
        ],
        
        // 企业商户-开户许可证验证规则
        accountOpeningLicenseImg: [
          { required: true, message: '请上传开户许可证照片', trigger: 'change' }
        ],
        
        // 经营场所照片验证规则
        businessPlaceImg: [
          { required: true, message: '请上传经营场所照片', trigger: 'change' }
        ],
        
        // 结算账户验证规则
        settlementType: [
          { required: true, message: '请选择账户类型', trigger: 'change' }
        ],
        bankName: [
          { required: true, message: '请输入开户银行', trigger: 'blur' }
        ],
        bankAccount: [
          { required: true, message: '请输入银行账户', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    // 根据审核状态判断是否可以编辑
    canEdit() {
      if (!this.accountInfo) return true; // 没有账户信息时可以编辑
      
      const status = this.accountInfo.auditStatus;
      // 只有暂存(99)或审核失败(2)状态可以编辑
      return status === '99' || status === '2';
    }
  },
  created() {
    this.getAccountInfo();
  },
  methods: {
    // 获取账户信息
    getAccountInfo() {
      this.loading = true;
      getAccountInfo().then(response => {
        this.loading = false;
        if (response.code === 200 && response.data) {
          this.accountInfo = response.data;
          
          // 设置账户类型
          this.accountType = response.data.accountType || '1';
          
          // 填充表单数据
          this.fillFormData(response.data);
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    
    // 填充表单数据
    fillFormData(data) {
      // 基本信息
      this.accountForm.accountId = data.accountId || '';
      this.accountForm.accountName = data.accountName || '';
      this.accountForm.accountType = data.accountType || '1';
      this.accountForm.contactPhone = data.contactPhone || '';
      this.accountForm.contactEmail = data.contactEmail || '';
      
      // 个人信息
      this.accountForm.idCardFrontImg = data.idCardFrontImg || '';
      this.accountForm.idCardBackImg = data.idCardBackImg || '';
      this.accountForm.accountHolder = data.accountHolder || '';
      this.accountForm.idCardNo = data.idCardNo || '';
      
      // 企业信息
      this.accountForm.businessLicenseImg = data.businessLicenseImg || '';
      this.accountForm.companyName = data.companyName || '';
      this.accountForm.unifiedSocialCreditCode = data.unifiedSocialCreditCode || '';
      
      // 法人信息
      this.accountForm.legalPersonIdCardFrontImg = data.legalPersonIdCardFrontImg || '';
      this.accountForm.legalPersonIdCardBackImg = data.legalPersonIdCardBackImg || '';
      this.accountForm.legalPersonName = data.legalPersonName || '';
      this.accountForm.legalPersonIdCardNo = data.legalPersonIdCardNo || '';
      
      // 开户许可证
      this.accountForm.accountOpeningLicenseImg = data.accountOpeningLicenseImg || '';
      
      // 经营场所
      this.accountForm.businessPlaceImg = data.businessPlaceImg || '';
      
      // 结算账户
      this.accountForm.settlementType = data.settlementType || '1';
      this.accountForm.bankName = data.bankName || '';
      this.accountForm.bankAccount = data.bankAccount || '';
    },
    
    // 账户类型变更
    handleAccountTypeChange(value) {
      this.accountForm.accountType = value;
      // 只在新建时重置表单
      if (!this.accountInfo || this.accountInfo.auditStatus === '99') {
        this.resetForm();
      }
    },
    
    // 上传前校验
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    
    // 上传成功回调
    handleUploadSuccess(res, field) {
      if (res.code === 200) {
        this.accountForm[field] = res.url || res.data.url;
      } else {
        this.$message.error('上传失败: ' + (res.msg || '未知错误'));
      }
    },
    
    // 提交表单
    submitForm(isSaveTemp) {
      if (isSaveTemp) {
        // 暂存功能，不进行表单验证，直接保存
        this.submitData(true);
        return;
      }
      
      this.$refs.accountFormRef.validate(valid => {
        if (valid) {
          this.submitData(false);
        }
      });
    },
    
    // 提交数据到服务器
    submitData(isTemp) {
      if (isTemp) {
        this.tempLoading = true;
      } else {
        this.submitLoading = true;
      }
      
      // 构造提交数据
      const formData = { ...this.accountForm };
      
      // 根据是否暂存选择不同的API
      const apiMethod = isTemp ? saveDraftAccount : saveAccount;
      
      apiMethod(formData).then(response => {
        if (isTemp) {
          this.tempLoading = false;
        } else {
          this.submitLoading = false;
        }
        
        if (response.code === 200) {
          this.$modal.msgSuccess(isTemp ? '暂存成功' : '提交成功');
          // 重新获取账户信息
          this.getAccountInfo();
        } else {
          this.$modal.msgError(response.msg || (isTemp ? '暂存失败' : '提交失败'));
        }
      }).catch(error => {
        if (isTemp) {
          this.tempLoading = false;
        } else {
          this.submitLoading = false;
        }
        console.error('保存支付账户信息失败:', error);
        this.$modal.msgError(isTemp ? '暂存失败' : '提交失败');
      });
    },
    
    // 重置表单
    resetForm() {
      if (this.$refs.accountFormRef) {
        this.$refs.accountFormRef.resetFields();
      }
      
      // 保留当前账户类型
      const currentType = this.accountType;
      
      // 重置表单基本信息
      this.accountForm = {
        accountId: this.accountForm.accountId, // 保留ID
        accountName: '',
        accountType: currentType,
        contactPhone: '',
        contactEmail: '',
        
        idCardFrontImg: '',
        idCardBackImg: '',
        accountHolder: '',
        idCardNo: '',
        
        businessLicenseImg: '',
        companyName: '',
        unifiedSocialCreditCode: '',
        
        legalPersonIdCardFrontImg: '',
        legalPersonIdCardBackImg: '',
        legalPersonName: '',
        legalPersonIdCardNo: '',
        
        accountOpeningLicenseImg: '',
        
        businessPlaceImg: '',
        
        settlementType: '1',
        bankName: '',
        bankAccount: ''
      };
    }
  }
};
</script>

<style scoped>
.alert-title {
  font-size: 16px;
  font-weight: bold;
}
.mt10 {
  margin-top: 10px;
}
.mt20 {
  margin-top: 20px;
}
.text-right {
  text-align: right;
}
.section-block {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.section-header {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
  font-size: 16px;
  font-weight: bold;
  background-color: #f5f7fa;
}
.section-content {
  padding: 20px;
}
.form-section-title {
  margin: 15px 0;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}
.form-input {
  width: 380px;
}
.form-date {
  width: 380px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.upload-box {
  width: 178px;
  height: 178px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}
.upload-box:hover {
  border-color: #409EFF;
  color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.upload-text {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}
.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}
</style> 